//Copyright (C) 2012 Chirila Alexandru
//This file is part of Robo-GoldMiner
//
//Robo-GoldMiner is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Robo-GoldMiner is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Robo-GoldMiner.  If not, see <http://www.gnu.org/licenses/>.


package gold;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * A function is a collection of Commands (that could also be functions).
 * The constructor of a function requires also the stack model, since the 
 * execution of the commands happens inside the function instance.
 * The stack model, executes and stacks any undoable commands. 
 * @author Alexandru Chirila
 */
public class Function implements Command, Serializable {

	private static final long serialVersionUID = -2586310269925099108L;
	
	private String name;
	
	private Maze m;
	private StackCommands cs;

	private ArrayList<Command> commands = new ArrayList<Command>();

	public Function(Maze m, StackCommands cs) {
		this.m = m;
		this.cs = cs;
	}

	@Override
	public boolean execute() throws EndGame, ParseException {
		if (m.isSkip()) {
			m.setSkip(false);
			return false;
		} else {
			for (Command comm : commands) {
				cs.execute(comm);
			}
			return true;
		}
	}

	/**
	 * Adds a command to the collection
	 * @param c command
	 */
	public void addCommand(Command c) {
		commands.add(c);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	private void writeObject(ObjectOutputStream stream) throws IOException {
		stream.defaultWriteObject();
	}

	private void readObject(ObjectInputStream stream) throws IOException,
			ClassNotFoundException {
		stream.defaultReadObject();
	}


}
